SPORE.$Import('core.request.base');

/*
---

name: Request.HTML

description: Extends the basic Request Class with additional methods for interacting with HTML responses.

license: MIT-style license.

requires: [Element, Request]

provides: Request.HTML

...
*/

SPORE.register('core.request.html',function($ns){

	Request.HTML = new Class({
	
		Extends: Request,
	
		options: {
			update: false,
			append: false,
			evalScripts: true,
			filter: false,
			headers: {
				Accept: 'text/html, application/xml, text/xml, */*'
			}
		},
	
		success: function(text){
			var options = this.options, response = this.response;
	
			response.html = text.stripScripts(function(script){
				response.javascript = script;
			});
	
			var match = response.html.match(/<body[^>]*>([\s\S]*?)<\/body>/i);
			if (match) response.html = match[1];
			var temp = new Element('div').set('html', response.html);
	
			response.tree = temp.childNodes;
			response.elements = temp.getElements('*');
	
			if (options.filter) response.tree = response.elements.filter(options.filter);
			if (options.update) document.id(options.update).empty().set('html', response.html);
			else if (options.append) document.id(options.append).adopt(temp.getChildren());
			if (options.evalScripts) Browser.exec(response.javascript);
	
			this.onSuccess(response.tree, response.elements, response.html, response.javascript);
		}
	
	});
	
	Element.Properties.load = {
	
		set: function(options){
			var load = this.get('load').cancel();
			load.setOptions(options);
			return this;
		},
	
		get: function(){
			var load = this.retrieve('load');
			if (!load){
				load = new Request.HTML({data: this, link: 'cancel', update: this, method: 'get'});
				this.store('load', load);
			}
			return load;
		}
	
	};
	
	Element.implement({
	
		load: function(){
			this.get('load').send(Array.link(arguments, {data: Type.isObject, url: Type.isString}));
			return this;
		}
	
	});

});